import { userUpdateInfo } from '../../services/usercenter/fetchPerson';
import { getStudentsPromise, clearStudentsPromise } from '../usercenter/students/edit/util';
import { setOpenId, setSelectedSchoolId, setSelectedStudentId, setUserId, setSelectedSchoolData, getUserId, setStudentsList, getStudentsList, getOpenId, setSchoolList, getSchoolList, setRight, getSelectedSchoolData, getRight, setUserName } from '../../userData/userData';
import { getSchoolFromCode, getAllStudent, addStudent, setDefaultStudent, getAllSchools, } from '../../services/students/studentData';
import Toast from 'tdesign-miniprogram/toast/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSchool: false,
    schoolName: "",
    name: "",
    relationship: "",
    relationships: [
      { label: '父亲' },
      { label: '母亲' },
      { label: '其他' },
    ],
    relationshipText: "选择关系",
    relationshipValue: "",
    relationshipVisible: false,
    hasSave: false
  },

  onLoad(options) {
    this.setData({
      schoolName: getSelectedSchoolData().name
    })
  },


  onShow() {

  },
  //选择关系
  onPicker() {
    this.setData({ relationshipVisible: true });
  },
  onColumnChange(e) {

  },
  onPickerChange(e) {
    const { key } = e.currentTarget.dataset;
    const { label } = e.detail;
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: label[0],
      [`${key}Text`]: label.join(' '),
    });
  },
  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log('picker cancel', e.detail);
    this.setData({
      [`${key}Visible`]: false,
    });
  },
  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    const { value = '' } = e.detail;
    this.setData(
      {
        [`${item}`]: value,
      },
    );
  },
  onRegister() {
    // debugger
    if (this.data.hasSave)
      return
    // if (!this.data.relationshipValue || this.data.relationshipValue == "") {
    //   Toast({
    //     context: this,
    //     selector: '#t-toast',
    //     message: "请选择关系",
    //     icon: '',
    //     duration: 1000,
    //   });
    //   return
    // }
    if (!this.data.name || this.data.name == "") {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请输入姓名",
        icon: '',
        duration: 1000,
      });
      return
    }
    this.setData({
      hasSave: true
    })
    userUpdateInfo(this.data).then((res) => {
      setUserName(this.data.name)
      this.onLoginHome(getStudentsList())
    })
  },
  onLoginHome(studentList) {
    let isDefault = false
    studentList.forEach(element => {
      if (element.i_id == this.data.school || getRight() == "tourist") {
        if (element.default == 1) {
          isDefault = true
          setSelectedStudentId(element._id)
          setSelectedSchoolId(element.i_id)
          if (getRight() == "tourist") {
            const schoolDate = getSchoolList()
            setSelectedSchoolData(schoolDate[element.i_id])
          }
          setRight("school")
          wx.switchTab({
            url: '/pages/home/home',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        }
      }
    });
    if (!isDefault) {
      this.waitForNewStudents()
      wx.navigateTo({
        url: '/pages/usercenter/students/edit/index'
      });
    }
  },
  waitForNewStudents() {
    clearStudentsPromise()
    getStudentsPromise()
      .then((newStudents) => {
        newStudents.default = 1
        console.log(newStudents)
        addStudent(newStudents).then((data) => {
          let studentList = getStudentsList()
          const schoolDate = getSchoolList()
          data.result[0].schoolName = schoolDate[data.result[0].i_id].name
          studentList.push(data.result[0])
          setStudentsList(studentList)
          setSelectedStudentId(data.result[0]._id)
          setSelectedSchoolId(data.result[0].i_id)
          wx.switchTab({
            url: '/pages/home/home',
            success: (res) => { },
            fail: (res) => { },
            complete: (res) => { },
          })
        })
      })
      .catch((e) => {
        this.setData({
          active: true
        })
        wx.navigateBack({ delta: 1 });
        if (e.message !== 'cancel') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '子女编辑发生错误',
            icon: '',
            duration: 1000,
          });
        }
      });
  },

})